const axios = require('axios')
const router = require('koa-router')()
const { models } = require('../../model')

router.get('/weather', async function (ctx) {
  const cityCode = ctx.request.query.cityCode
  const cacheValidTime = new Date(new Date() - 3600 * 1000 * 2)
  let weatherData
  const weatherDoc = await models.CityWeather.findOne({
    cityCode: cityCode,
    createdAt: {
      $gte: cacheValidTime
    }
  })
  if (!weatherDoc) {
    const res = await axios.get(`http://t.weather.itboy.net/api/weather/city/${cityCode}`)
    weatherData = res.data
    await models.CityWeather.insertOne({
      cityCode: cityCode,
      data: weatherData
    })
  } else {
    weatherData = weatherDoc.data
  }
  ctx.wrapper.succ(weatherData)
})

router.get('/city', async function (ctx) {
  const cities = await models.City.find({
    pid: {
      $regex: /^0$|^[0-2]?[0-9]$|^3[0-4]$/
    }
  }).toArray()

  const provinces = cities.filter(province => +province.id <= 34).map(province => {
    province.cities = cities.filter(city => city.pid === province.id)
    return province
  })

  ctx.wrapper.succ(provinces)
})

module.exports = router
